package script;

import org.luaj.vm2.*;
import org.luaj.vm2.lib.jse.*;
import java.util.*;

public class LuaJavaDemo {

    // 示例1：静态工具类
    public static class StaticUtils {
        public static String reverseString(String s) {
            return new StringBuilder(s).reverse().toString();
        }
    }

    // 示例5：数组访问
    public static class ArrayHolder {
        public static int[] numbers = {10, 20, 30};
    }

    // 示例3：接口定义
    public interface TextProcessor {
        String process(String input);
    }

    // 示例10：事件监听接口
    public interface EventListener {
        void onEvent(String message);
    }

    // 示例9：异常测试
    public static class FileUtils {
        public static void riskyOperation() throws Exception {
            throw new Exception("模拟的Java异常");
        }
    }

    public static void main(String[] args) {
        Globals globals = JsePlatform.standardGlobals();

        // 暴露Java对象到Lua
        globals.set("StaticUtils", CoerceJavaToLua.coerce(StaticUtils.class));
        globals.set("ArrayHolder", CoerceJavaToLua.coerce(ArrayHolder.class));
        globals.set("FileUtils", CoerceJavaToLua.coerce(FileUtils.class));
        globals.set("ArrayList", CoerceJavaToLua.coerce(ArrayList.class));

        // 加载并执行Lua脚本
        LuaValue chunk = globals.loadfile("demo.lua");
        chunk.call();

        // 示例2：操作Lua Table
        System.out.println("\n[Java] 操作Lua Table:");
        LuaValue userTable = globals.get("userTable");
        System.out.println("原始年龄: " + userTable.get("age"));
        userTable.set("age", LuaValue.valueOf(25));
        System.out.println("修改后年龄: " + userTable.get("age"));

        // 示例3：调用Lua实现的接口
        LuaTable luaProcessorLT = (LuaTable) globals.get("luaProcessor");
        LuaClosure process = (LuaClosure) luaProcessorLT.get("process");
        System.out.println(process.call(LuaValue.valueOf("Hello, Lua!")));


        // 示例4：协程控制
        System.out.println("\n[Java] 协程输出:");
        LuaValue coroutine = globals.get("numberCoroutine");
        for (int i = 0; i < 3; i++) {
            LuaValue result = globals.load("return coroutine.resume(...)").call(coroutine);
            System.out.println("协程返回值: " + result.arg(2));
        }

        // 示例8：调用Lua闭包
        System.out.println("\n[Java] 调用Lua闭包:");
        LuaValue counter = globals.get("createCounter").call();
        System.out.println("计数1: " + counter.call());
        System.out.println("计数2: " + counter.call());

        // 示例10：触发回调
        LuaTable luaListenerLT = (LuaTable) globals.get("luaListener");
        LuaClosure onEvent = (LuaClosure) luaListenerLT.get("onEvent");
        LuaValue eventResult = onEvent.call(LuaValue.valueOf("触发回调参数"));
        System.out.println("回调返回结果：" + eventResult);
    }
}
